package com.wjk.kylin.core.security;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.wjk.kylin.core.common.data.ResponseData;
import com.wjk.kylin.core.constant.CommonConstant;
import com.wjk.kylin.core.constant.Constants;
import com.wjk.kylin.core.utils.IpUtils;
import com.wjk.kylin.modules.system.log.entity.OperateLog;
import com.wjk.kylin.modules.system.log.service.ILogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenUtil jwtTokenUtil;
    @Autowired
    private ILogService logService;
    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        log.info("================================退出处理=====================================");

        String json = JSONObject.toJSONString(ResponseData.success(HttpStatus.HTTP_OK,"退出成功"));

        //清除token
        String authHeader = request.getHeader(Constants.TOKEN_HEADER);
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith(Constants.TOKEN_TYPE_BEARER)) {
            final String authToken = StringUtils.substring(authHeader, 7);
            AuthUser authUser = (AuthUser) jwtTokenUtil.getUserDetails(authToken);
            if(authUser != null){
                log.info("清除token以及用户信息,authToken:{},username:{},id:{}",authToken,authUser.getUsername(),authUser.getId());
                jwtTokenUtil.removeToken(authToken);

                // 退出日志log
                saveLogoutLog(request, json, authUser.getUsername());

            }
        }

        log.info("请求访问：{}，用户退出登录，json信息：{}",request.getRequestURI(),json);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }

    /**
     * 保存退出日志
     * @param request
     * @param json
     * @param username 操作人员username
     */
    private void saveLogoutLog(HttpServletRequest request, String json, String username) {
        OperateLog operateLog = new OperateLog();
        operateLog.setStatus(CommonConstant.BusinessStatus.SUCCESS.getCode());
        // 请求的地址
        String ip = IpUtils.getIpAddr(request);
        operateLog.setIp(ip);
        // 返回参数
        operateLog.setResponseData(json);
        operateLog.setUrl(request.getRequestURI());
        // 设置方法名称
        operateLog.setMethod("com.wjk.kylin.core.security.onLogoutSuccess()");
        // 设置请求方式
        operateLog.setRequestMethod(request.getMethod());
        // 设置action动作
        operateLog.setBusinessType(CommonConstant.BusinessType.OTHER.getCode());
        // 设置标题
        operateLog.setTitle("登出");
        // 保存request，参数和值
//        operateLog.setRequestData(null);
        //create by
        operateLog.setCreateBy(username);
        // 写入数据库当中
        logService.save(operateLog);
    }
}
